package user

import (
	"im-mq/db"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

func Init_Once(app *gin.Engine) {
	userApp := app.Group("/user")
	userApp.POST("/login", func(c *gin.Context) {
		// id and pwd, then return token
		strID := c.DefaultPostForm("uid", "")
		strPwd := c.DefaultPostForm("pwd", "")
		token := db.User_login(strID, strPwd)
		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  token,
		})
	})
	userApp.POST("/logout", func(c *gin.Context) {
		strToken := c.DefaultPostForm("token", "")
		strOk := "Logout Failed!"
		if db.User_logout(strToken) {
			strOk = "Logout OK!"
		}
		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  strOk,
		})
	})
	userApp.POST("/ping", func(c *gin.Context) {
		// userid and token, update or get ttl
		strToken := c.DefaultPostForm("token", "")
		var nCode int32 = -100
		if db.Session_Get(strToken) != "" {
			nCode = db.Session_TTL_UP(strToken)
		}
		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  strconv.Itoa(int(nCode)),
		})
	})
	userApp.POST("/info", func(c *gin.Context) {
		// userid and token, get user info
		strToken := c.DefaultPostForm("token", "")
		tID := db.Session_Get(strToken)
		if len(tID) < 1 {
			c.JSON(http.StatusOK, gin.H{
				"code": 403,
				"msg":  "token error!",
			})
			return
		}
		var objRet = db.User_Info(tID)

		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  objRet,
		})
	})
	userApp.POST("/friends", func(c *gin.Context) {
		// userid and token, get user info
		strToken := c.DefaultPostForm("token", "")
		tID := db.Session_Get(strToken)
		if len(tID) < 1 {
			c.JSON(http.StatusOK, gin.H{
				"code": 403,
				"msg":  "token error!",
			})
			return
		}
		var objRet = db.User_Info2(tID)
		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  objRet,
		})

	})
	userApp.POST("/groups", func(c *gin.Context) {
		// userid and token, get user info
		strToken := c.DefaultPostForm("token", "")
		tID := db.Session_Get(strToken)
		if len(tID) < 1 {
			c.JSON(http.StatusOK, gin.H{
				"code": 403,
				"msg":  "token error!",
			})
			return
		}
		var objRet = db.User_Info3(tID)
		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  objRet,
		})

	})
}
